import { useUserStore } from '@/stores'
import axios, { type Method } from 'axios'
import { showToast } from 'vant'
import router from '@/router'

// 1. 创建一个axios实例对象
const baseURL = 'https://consult-api.itheima.net'
const instance = axios.create({
  baseURL,
  timeout: 10000
})

// 2. 配置请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 判断是否有token
    const store = useUserStore()
    if (store.user?.token && config.headers) {
      config.headers['Authorization'] = `Bearer ${store.user?.token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 3. 配置响应拦截器
instance.interceptors.response.use(
  (res) => {
    // 3.1 请求成功但操作失败
    if (res.data?.code !== 10000) {
      // 3.1.1 提示用户
      showToast(res.data?.message || '业务操作失败')
      // 3.1.2 抛出错误
      return Promise.reject(res.data)
    }
    return res.data
  },
  (error) => {
    // 3.2 处理401错误
    if (error.response.status === 401) {
      // 3.2.1 清空用户信息
      const store = useUserStore()
      store.delUser()

      // 3.2.2 跳转到登录页
      router.push({
        path: '/login',
        query: { returnUrl: router.currentRoute.value.fullPath }
      })
    }
    return Promise.reject(error)
  }
)

// 4. 封装请求工具函数
type Data<T> = {
  code: number
  message: string
  data: T
}

const request = <T>(
  url: string,
  method: Method = 'GET',
  submitData?: object
) => {
  return instance.request<T, Data<T>>({
    url,
    method,
    [method.toLowerCase() === 'get' ? 'params' : 'data']: submitData
  })
}

export { instance, baseURL, request }
